/**
 *
 * myuitl/get_accesstoken.js
 * 获取  access_token
 *
 */

const axios = require('axios');


//有效期  number
const EXPIRE = 7000*1000;

//最近一次获取 aceess_token 时间
let start_at = 0;

// Promise
let p = null;

//结果
let accesstoken_data = {};


// 异常处理交给调用者,调用结果也交给调用者
//除非网络异常，不然不会throw error

/**
 *
 * 正常返回  {"access_token":"ACCESS_TOKEN","expires_in":7200}
 * 
 * 异常返回 {"errcode":40013,"errmsg":"invalid appid"}
 * 
 */
module.exports = async (appid, appsecret)=>{


    //正在获取中
    if(p){

        //console.log('获取中');

        let { data } = await p;

        return data

    //过期了 或 上次有误
    }else if(Date.now()-start_at>EXPIRE || accesstoken_data.errcode ){

        //console.log('新加载');

        p =  axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`);

        try{

            let { data } = await p;

            accesstoken_data = data;

            if(data.access_token){

                start_at = Date.now();
            }

        }catch(e){

            throw e

        }finally{

            //非加载状态
            p = null
        }


    }


    return accesstoken_data


}